﻿using System;

namespace _027.自定义list
{
	class MyList<T>
	{
		private T[] data = new T[0]; // data null

		// 元素个数
		private int count = 0;
		// 容量
		public int Capacity
		{
			get
			{
				return data.Length;
			}
		}

		// 元素的个数
		public int Count
		{
			get
			{
				return count;
			}
		}

		// add
		public void Add(T item)
		{
			// 如果长度为0 初始化为4
			if (data.Length == 0)
			{
				data = new T[4];
			}
			// 添加元素之前要判断是否已满
			if (data.Length == count)
			{
				T[] temp = new T[count * 2];
				for (int i = 0; i < data.Length; i++)
				{
					temp[i] = data[i];
				}
				data = temp;
			}
			data[count] = item;
			count++;
		}

		// 索引器
		public T this[int index]
		{
			get
			{
				if (index < 0 || index > Count - 1)
				{
					throw new ArgumentOutOfRangeException("索引超出范围");
				}
				return data[index];
			}
			set
			{
				data[index] = value;
			}
		}

		// 插入
		public void Insert(int index, T item)
		{
			if (index < 0 || index > count - 1)
			{
				throw new ArgumentOutOfRangeException("索引超出范围");
			}
			for (int i = count - 1; i > index - 1; i--)
			{
				data[i + 1] = data[i];
			}
			data[index] = item;
			count++;
		}
		// 移除元素
		public void RemoveAt(int index)
		{
			if (index < 0 || index > count - 1)
			{
				throw new ArgumentOutOfRangeException("索引超出范围");
			}
			for (int i = index + 1; i < count; i++)
			{
				data[i - 1] = data[i];
			}
			count--;
		}

		public int IndexOf(T item)
		{
			int index = -1;
			for (int i = 0; i < count; i++)
			{
				if (item.Equals(data[i]))
				{
					return i;
				}
			}
			return index;
		}

		public int LastyIndexOf(T item)
		{
			int index = -1;
			for (int i = count - 1; i >= 0; i--)
			{
				if (item.Equals(data[i]))
				{
					return i;
				}
			}
			return index;
		}

		public void Sort()
		{
			Array.Sort(data, 0, count);
		}
	}
}
